package com.lthlearn.controller;

import com.lthlearn.pojo.Result;
import com.lthlearn.pojo.User;
import com.lthlearn.service.UserService;
import com.lthlearn.util.EmailUtil;
import com.lthlearn.util.JWTUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author: 2942733239@qq.com
 * @date: 2024/11/4 11:10
 * @description: com.lthlearn.controller
 * @version: 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("sendCode")
    public Result sendCode(String email) {
        // 1.根据邮箱查找用户
        User user = userService.getByEmail(email);
        // 2.用户是否存在
        if (user == null) {
            // 不存在，返回错误
            return new Result("500", "用户不存在");
        }
        // 存在，验证邮箱
        int n = (int) (Math.random() * 90000 + 10000);
        String serverCode = String.valueOf(n);
        emailUtil.send(email, serverCode);
        // 3.存入 (session) redis
        redisTemplate.opsForValue().set(email, serverCode, 1, TimeUnit.MINUTES);
        // 4.发送验证码
        return new Result("200", "发送验证码成功", user);
    }

    @PostMapping("login")
    public Result login(String email, String code) {
        // 1.判断 email 是否存在
        User user = userService.getByEmail(email);
        if (user == null) {
            return new Result("404", "邮箱不存在");
        }
        // 存在，获取验证码
        // 2.从 redis 中根据邮箱获取验证码
        String serverCode = (String) redisTemplate.opsForValue().get(email);
        if (serverCode == null) {
            // 过期
            return new Result("505", "sorry,验证码已过期");
        }
        if (!serverCode.equals(code)) {
            // 不正确
            return new Result("500", "sorry,验证码不正确");
        }
        // 登录成功
        // 3.生成一个 token，记录用户登录状态
        String token = JWTUtils.geneJsonWebToken(user);
        return new Result("200", "登录成功!", token);
    }

    /**
     * 获取当前用户所有收藏
     *
     * @param token
     * @return
     */
    @GetMapping("getAllCollect")
    public Result searchAll(@RequestParam(value = "token") String token) {
        Claims claims = JWTUtils.checkJWT(token);
        // 校验登录状态
        if (claims != null && claims.get("id") != null) {
            // 已登录
            return userService.getCollectByUserIdAndPlaceIds((Integer) claims.get("id"));
        }
        // 未登录
        return new Result("500", "查询失败，未登录");
    }

}
